package service

import (
	"fmt"
	"github.com/go-resty/resty/v2"
	"log"
	"main/internal/zodiac/models"
	"main/internal/zodiac/storage"
	"os"
	"reflect"
	"strings"
)

type ExchangeApi struct {
	baseURL string
	repo    storage.RateHistoryRepository
}

var _ RateService = (*ExchangeApi)(nil)

func NewExchangeApi(baseURL string, repo storage.RateHistoryRepository) *ExchangeApi {
	return &ExchangeApi{repo: repo, baseURL: baseURL}
}

/*
*
https://v6.exchangerate-api.com/v6/{{apikey}}/history/AED/2025/03/04
*/
func (e *ExchangeApi) History(base_currency string, record_date string) ([]models.RateHistory, error) {
	client := resty.New()
	var exchangeApiResponse *ExchangeApiHistoryResponse

	var rateHistoryList []models.RateHistory

	apiKey := os.Getenv("EXCHANGE_API_KEY")
	uri := e.baseURL + apiKey + "/history/" + base_currency + "/" + record_date
	resp, err := client.R().
		SetResult(&exchangeApiResponse).
		Get(uri)
	if err != nil {
		log.Fatalf("Error making request: %v", err)
	}
	fmt.Println("Http Status:", resp.Status())
	fmt.Println("Response:", exchangeApiResponse)

	conversionRates := reflect.ValueOf(exchangeApiResponse.ConversionRates)
	conversionRatesType := conversionRates.Type()
	for i := 0; i < conversionRates.NumField(); i++ {
		field := conversionRates.Field(i)
		fieldName := strings.ToUpper(conversionRatesType.Field(i).Name)
		fieldValue := field.Interface()

		var rate float64
		switch v := fieldValue.(type) {
		case float64:
			rate = v
		case int:
			rate = float64(v)
		case float32:
			rate = float64(v)
		default:
			continue
		}

		rateHistory := models.RateHistory{
			RecordDate:     fmt.Sprintf("%d-%02d-%02d", exchangeApiResponse.Year, exchangeApiResponse.Month, exchangeApiResponse.Day),
			BaseCurrency:   exchangeApiResponse.BaseCode,
			TargetCurrency: fieldName,
			Rate:           rate,
		}
		rateHistoryList = append(rateHistoryList, rateHistory)
	}
	//异步保存到数据库
	go func() {
		if saveError := e.repo.SaveRateHistory(rateHistoryList); saveError != nil {
			log.Printf("Error saving rate history: %v", saveError)
		}
	}()

	return rateHistoryList, nil
}

func (e *ExchangeApi) Pair(base_currency string, target_currency string) (models.RateHistory, error) {
	//TODO implement me
	panic("implement me")
}
